package client;

import java.io.IOException;

import shared.network.messages.TextMessage;

import client.appstate.AppSettingLoader;
import client.appstate.PlayState;
import client.network.ClientListener;

import com.jme3.app.SimpleApplication;
import com.jme3.input.ChaseCamera;
import com.jme3.network.Client;
import com.jme3.network.Network;
import com.jme3.network.serializing.Serializer;
import com.jme3.system.JmeContext;

public class ClientMain extends SimpleApplication{

	public final String SERVERADDRESS = "localhost";
	public final int PORT = 6143;
	
	Client client;
	PlayState ps;
	
	private boolean camChange = true;
	
	public ClientMain()
	{
		super();
	}
	
	@Override
	public void simpleInitApp() {
		
		
		flyCam.setEnabled(true);
		flyCam.setMoveSpeed(10);
		flyCam.setRotationSpeed(5);
		
		
		try {
			// Register Classes
			Serializer.registerClass(TextMessage.class);
			
			//Initialize Network Connection to Server
			client = Network.connectToServer(SERVERADDRESS,PORT);
			client.start();
			
			
		} catch (IOException e) {
			//TODO Exceptionhandling
			e.printStackTrace();
			return;
		}
				
		client.addMessageListener(new ClientListener());
		
		ps = new PlayState();
		ps.initialize(stateManager, this);
		ps.setEnabled(true);
		
	}
	
	@Override
	public void simpleUpdate(float tpf) {
		if((camChange==true)&&(rootNode.getChild("vehicleNode")!=null))
		{
			flyCam.setEnabled(false);
			ChaseCamera chaseCam = new ChaseCamera(cam, rootNode.getChild("vehicleNode"), inputManager);
			chaseCam.setMinDistance(10f);
			chaseCam.setMaxDistance(500f);
			chaseCam.setSmoothMotion(true);
			chaseCam.setDefaultDistance(30f);
			chaseCam.setDragToRotate(false);
			chaseCam.setInvertVerticalAxis(true);
			chaseCam.setTrailingSensitivity(0.7f);
			chaseCam.setTrailingEnabled(true);
			camChange=false;
		}
		super.simpleUpdate(tpf);
	}
	
	@Override
	public void destroy() {
		try
		{
			client.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	    super.destroy();
	}
	
	public static void main(String args[])
	{
		ClientMain app = new ClientMain();
		app.setSettings(AppSettingLoader.getDefaultAppSettings());
		app.start(JmeContext.Type.Display);
	}

}
